//
//  VerCodeViewController.m
//  fitnessmanage
//
//  Created by 众拳科技 on 2017/10/17.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//  输入验证码页面

#import "VerCodeViewController.h"
#import "VerCodeView.h"
#import "PerfectViewController.h"
#import "SetPassViewController.h"
#import "LoginDetailViewController.h"

@interface VerCodeViewController (){
    
    NSTimer *_timer;
    
    int _count;
}

@property(nonatomic,weak)VerCodeView *verCodeView;

@end

@implementation VerCodeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];

    self.view.backgroundColor = CSWhiteColor;
    
    _count = 30;
    
    VerCodeView *verCodeView = [[VerCodeView alloc] initWithFrame:self.view.frame];
    
    verCodeView.from = self.from;
    
    [verCodeView.nextBtn addTarget:self action:@selector(goToPerfect) forControlEvents:UIControlEventTouchUpInside];
    
    verCodeView.titleLabel.text = self.from;
    
    //密码明文暗文切换
    [verCodeView.lookBtn addTarget:self action:@selector(passwordChange:)forControlEvents:UIControlEventTouchUpInside];
    
    //点击获取验证码
    [verCodeView.sendVercodeBtn addTarget:self action:@selector(sendVerCodeBtnClick:)forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:verCodeView];
    
    self.verCodeView = verCodeView;
}

#pragma mark 下一步
-(void)goToPerfect{
    
    //先验证是不是手机号码
    NSString *mobile = self.verCodeView.phoneTF.text;
    
    if (![mobile isMobileNumber]) {
        [MBProgressHUD showText:@"请输入正确的手机号码" toview:self.view];

        
        return;
    }
    
    NSString *verCode = self.verCodeView.vercodeTF.text;
    
    if (!verCode || verCode.length == 0) {
        
        [MBProgressHUD showText:@"请输入验证码" toview:self.view];

        
        return;
    }
    
    
    if ([self.from isEqualToString:@"忘记密码"]) {
        
        NSString *pwd = self.verCodeView.passWordTF.text;
        
        if (!pwd || pwd.length == 0) {
            
            [MBProgressHUD showText:@"请输入密码" toview:self.view];
            
            return;
        }
        
        [self chagePassWord:verCode andPhone:mobile];
    }
    else{
        
        [self checkVerCode:verCode andPhone:mobile];
    }
}


#pragma mark 检查手机号是否注册
-(void)checkMobileIsReg:(UIButton *)sender{
    
    //先验证是不是手机号码
    NSString *mobile = self.verCodeView.phoneTF.text;
    
    if (![mobile isMobileNumber]) {
        
        [MBProgressHUD showText:@"请输入正确的手机号码" toview:self.view];
        
        return;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:mobile forKey:@"phone"];
    
    [HTTPTool GET:Get_CheckPhoneReg parameters:params success:^(id responseObject) {
        
        if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){
            
            if ([[responseObject objectForKey:@"Exists"] integerValue] == 0) {
                
                
                [self startTimerWithButton:sender];
                
                NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                
                [params setObject:mobile forKey:@"PhoneNumber"];
                
                [HTTPTool POSTRaw:Post_Home_SendSMS parameters:params success:^(id responseObject) {
                    
                    if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){
                        
                        [MBProgressHUD showText:@"发送验证码成功"];
                    }
                    else{
                        
                        [MBProgressHUD showText:@"请输入正确的手机号"];
                    }
                    
                } failure:^(NSError *error) {
                    
                }];
            }
            else{
                
                [MBProgressHUD showText:@"该手机号已经注册"];
            }
        }
        else{
            
            [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
        }
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD showText:@"验证失败"];
    }];
}


/**
 修改密码
 */
-(void)chagePassWord:(NSString *)verCode andPhone:(NSString *)phone{
    
    //Post_Change_Pwd
//    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:phone forKey:@"PhoneNumber"];
    
    [params setObject:verCode forKey:@"Code"];
    
    [params setObject:self.verCodeView.passWordTF.text forKey:@"Pwd"];
    
    [HTTPTool POSTRaw:Post_Change_Pwd parameters:params success:^(id responseObject) {

        if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){

            [MBProgressHUD showText:@"修改成功"];

            for (UIViewController *controller in self.navigationController.viewControllers) {

                if ([controller isKindOfClass:[LoginDetailViewController class]]) {

                    LoginDetailViewController *loginDetailVC =(LoginDetailViewController *)controller;

                    [self.navigationController popToViewController:loginDetailVC animated:YES];
                }
            }

        }
        else{

            [MBProgressHUD showText:@"请输入正确的手机号"];
        }

    } failure:^(NSError *error) {

    }];
}

/**
 检查验证码
 */
-(void)checkVerCode:(NSString *)verCode andPhone:(NSString *)phone{
    
    
    

    
    
    //Post_Home_CheckCode
    //请求token、key
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:verCode forKey:@"Code"];
    
    [params setObject:phone forKey:@"PhoneNumber"];
    
    [HTTPTool POSTRaw:Post_Home_CheckCode parameters:params success:^(id responseObject) {

        [MBProgressHUD hideHUDForView:self.view];

        if (responseObject && [[responseObject objectForKey:@"code"] intValue] == 0){

            UserAccount *userAccount = [UserAccount account];

            //userAccount.userAccount = phone;

            userAccount.CellPhone = phone;

            [UserAccount saveAccount:userAccount];

            
            if ([self.from isEqualToString:@"忘记密码"]) {
                
                SetPassViewController *setPassVC = [[SetPassViewController alloc] init];
                
                [self.navigationController pushViewController:setPassVC animated:YES];
            }
            else{
                
                //跳转设置登录密码页面
                PerfectViewController *perfectVC = [[PerfectViewController alloc] init];
                
                [self.navigationController pushViewController:perfectVC animated:YES];
                
            }

            }
        else{

            [MBProgressHUD showText:@"请输入正确的验证码"];
        }

    } failure:^(NSError *error) {

        [MBProgressHUD hideHUDForView:self.view];
    }];
    
}

#pragma mark 密码切换
-(void)passwordChange:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    
    self.verCodeView.passWordTF.secureTextEntry = !self.verCodeView.passWordTF.secureTextEntry;
    
    NSString* text = self.verCodeView.passWordTF.text;
    
    self.verCodeView.passWordTF.text = @" ";
    
    self.verCodeView.passWordTF.text = text;
}

#pragma mark 获取验证码
-(void)sendVerCodeBtnClick:(UIButton *)sender{
    
    
    
    //验证手机号是否注册过
    
    [self checkMobileIsReg:sender];
    
    
}

//启动定时器
- (void)startTimerWithButton:(UIButton *)button
{
    button.enabled = NO;
    
    if (!_timer) {
        
        _timer = [[NSTimer alloc]initWithFireDate:[NSDate date] interval:1 target:self selector:@selector(count:) userInfo:button repeats:YES];
        
        [[NSRunLoop mainRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

//倒计时
- (void)count:(NSTimer *)timer
{
    UIButton *button = timer.userInfo;
    
    if (_count == 0) {
        
        button.enabled = YES;
        
        [_timer invalidate];
        
        _timer = nil;
        
        _count = 30;
    }
    _count --;
    [button setTitle:[NSString stringWithFormat:@"%d S",_count] forState:UIControlStateDisabled];
}

-(void)dealloc{
    
    [_timer invalidate];
    
    _timer = nil;
}

@end
